<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>经典贪吃蛇游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#FF5722',
                        dark: '#212121',
                        light: '#F5F5F5',
                    },
                    fontFamily: {
                        game: ['"Press Start 2P"', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .pixel-corners {
                clip-path: polygon(
                    0% 4px, 4px 4px, 4px 0%, calc(100% - 4px) 0%, 
                    calc(100% - 4px) 4px, 100% 4px, 100% calc(100% - 4px), 
                    calc(100% - 4px) calc(100% - 4px), calc(100% - 4px) 100%, 
                    4px 100%, 4px calc(100% - 4px), 0% calc(100% - 4px)
                );
            }
            .game-shadow {
                box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.2), 
                            inset 0 0 0 4px rgba(0, 0, 0, 0.1);
            }
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-900 min-h-screen flex flex-col items-center justify-center p-4 text-light font-game">
    <div class="max-w-4xl w-full mx-auto">
        <!-- 游戏标题 -->
        <header class="text-center mb-6">
            <h1 class="text-[clamp(2rem,5vw,3rem)] text-primary mb-2 tracking-wider">贪吃蛇大作战</h1>
            <p class="text-gray-400 text-sm md:text-base">使用方向键或WASD控制蛇的移动，吃到食物增长得分</p>
        </header>

        <!-- 游戏区域 -->
        <div class="relative w-full bg-dark rounded-lg pixel-corners game-shadow overflow-hidden">
            <!-- 游戏画布 -->
            <canvas id="gameCanvas" class="w-full h-auto block"></canvas>
            
            <!-- 游戏控制按钮 - 移动设备 -->
            <div class="absolute bottom-4 left-0 right-0 flex justify-center space-x-4 md:hidden">
                <button id="upBtn" class="bg-primary/80 hover:bg-primary text-white w-16 h-16 rounded-full flex items-center justify-center transition-all active:scale-95">
                    <i class="fa fa-chevron-up text-xl"></i>
                </button>
                <div class="flex flex-col space-y-2">
                    <button id="leftBtn" class="bg-primary/80 hover:bg-primary text-white w-16 h-16 rounded-full flex items-center justify-center transition-all active:scale-95">
                        <i class="fa fa-chevron-left text-xl"></i>
                    </button>
                    <button id="rightBtn" class="bg-primary/80 hover:bg-primary text-white w-16 h-16 rounded-full flex items-center justify-center transition-all active:scale-95">
                        <i class="fa fa-chevron-right text-xl"></i>
                    </button>
                </div>
                <button id="downBtn" class="bg-primary/80 hover:bg-primary text-white w-16 h-16 rounded-full flex items-center justify-center transition-all active:scale-95">
                    <i class="fa fa-chevron-down text-xl"></i>
                </button>
            </div>
            
            <!-- 游戏开始界面 -->
            <div id="startScreen" class="absolute inset-0 bg-dark/90 flex flex-col items-center justify-center z-10">
                <h2 class="text-2xl text-primary mb-6">准备开始</h2>
                <button id="startBtn" class="bg-primary hover:bg-primary/80 text-white px-8 py-4 rounded-lg transition-all active:scale-95 mb-4">
                    <i class="fa fa-play mr-2"></i>开始游戏
                </button>
                <p class="text-gray-400 text-sm">最高纪录: <span id="highScoreDisplay">0</span></p>
            </div>
            
            <!-- 游戏暂停界面 -->
            <div id="pauseScreen" class="absolute inset-0 bg-dark/90 flex flex-col items-center justify-center z-10 hidden">
                <h2 class="text-2xl text-primary mb-6">游戏暂停</h2>
                <button id="resumeBtn" class="bg-primary hover:bg-primary/80 text-white px-8 py-4 rounded-lg transition-all active:scale-95 mb-4">
                    <i class="fa fa-play mr-2"></i>继续游戏
                </button>
            </div>
            
            <!-- 游戏结束界面 -->
            <div id="gameOverScreen" class="absolute inset-0 bg-dark/90 flex flex-col items-center justify-center z-10 hidden">
                <h2 class="text-2xl text-secondary mb-2">游戏结束</h2>
                <p class="text-white mb-6">你的得分: <span id="finalScore">0</span></p>
                <button id="restartBtn" class="bg-primary hover:bg-primary/80 text-white px-8 py-4 rounded-lg transition-all active:scale-95 mb-4">
                    <i class="fa fa-refresh mr-2"></i>再来一局
                </button>
                <p class="text-gray-400 text-sm">最高纪录: <span id="gameOverHighScore">0</span></p>
            </div>
        </div>

        <!-- 游戏信息和控制 -->
        <div class="flex flex-col md:flex-row justify-between items-center mt-6 gap-4">
            <div class="flex items-center gap-4">
                <div class="bg-dark rounded-lg px-4 py-2 pixel-corners game-shadow">
                    <span class="text-gray-400 text-sm">得分:</span>
                    <span id="scoreDisplay" class="text-white ml-2">0</span>
                </div>
                <div class="bg-dark rounded-lg px-4 py-2 pixel-corners game-shadow">
                    <span class="text-gray-400 text-sm">长度:</span>
                    <span id="lengthDisplay" class="text-white ml-2">3</span>
                </div>
            </div>
            
            <div class="flex items-center gap-4">
                <button id="pauseBtn" class="bg-dark hover:bg-gray-80 text-white px-4 py-2 rounded-lg transition-all active:scale-95 flex items-center">
                    <i class="fa fa-pause mr-2"></i>暂停
                </button>
                <button id="soundBtn" class="bg-dark hover:bg-gray-80 text-white w-10 h-10 rounded-lg transition-all active:scale-95 flex items-center justify-center">
                    <i id="soundIcon" class="fa fa-volume-up"></i>
                </button>
            </div>
        </div>

        <!-- 游戏说明 -->
        <div class="mt-8 bg-dark/50 rounded-lg p-4 pixel-corners game-shadow">
            <h3 class="text-primary mb-3 text-lg">游戏说明</h3>
            <ul class="text-gray-300 text-sm space-y-2">
                <li><i class="fa fa-keyboard-o mr-2"></i>电脑端：使用方向键或WASD控制蛇的移动</li>
                <li><i class="fa fa-mobile mr-2"></i>移动端：点击屏幕下方的方向按钮控制</li>
                <li><i class="fa fa-plus-circle mr-2"></i>吃到食物：蛇的长度增加，分数提高</li>
                <li><i class="fa fa-exclamation-triangle mr-2"></i>游戏结束：撞到墙壁或自己的身体</li>
                <li><i class="fa fa-star mr-2"></i>特殊食物：每隔一段时间会出现特殊食物，吃到后获得额外分数</li>
            </ul>
        </div>
    </div>

    <footer class="mt-12 text-center text-gray-500 text-xs">
        <p>© 2025 贪吃蛇大作战 | 经典游戏重现</p>
    </footer>

    <script>
        // 游戏常量
        const GRID_SIZE = 20;
        const INITIAL_SPEED = 150;
        const MIN_SPEED = 80;
        const SPEED_INCREMENT = 2;
        const SPECIAL_FOOD_DURATION = 5000; // 特殊食物持续时间（毫秒）
        const SPECIAL_FOOD_SCORE = 10; // 特殊食物分数
        const NORMAL_FOOD_SCORE = 1; // 普通食物分数

        // 游戏变量
        let canvas, ctx;
        let snake = [];
        let food = {};
        let specialFood = null;
        let direction = 'right';
        let nextDirection = 'right';
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let snakeLength = 3;
        let gameSpeed = INITIAL_SPEED;
        let gameLoopId = null;
        let isPaused = false;
        let isGameOver = false;
        let soundEnabled = true;
        let specialFoodTimer = null;
        let specialFoodVisible = false;

        // DOM 元素
        const startScreen = document.getElementById('startScreen');
        const pauseScreen = document.getElementById('pauseScreen');
        const gameOverScreen = document.getElementById('gameOverScreen');
        const startBtn = document.getElementById('startBtn');
        const pauseBtn = document.getElementById('pauseBtn');
        const resumeBtn = document.getElementById('resumeBtn');
        const restartBtn = document.getElementById('restartBtn');
        const soundBtn = document.getElementById('soundBtn');
        const soundIcon = document.getElementById('soundIcon');
        const scoreDisplay = document.getElementById('scoreDisplay');
        const lengthDisplay = document.getElementById('lengthDisplay');
        const highScoreDisplay = document.getElementById('highScoreDisplay');
        const finalScore = document.getElementById('finalScore');
        const gameOverHighScore = document.getElementById('gameOverHighScore');
        const upBtn = document.getElementById('upBtn');
        const downBtn = document.getElementById('downBtn');
        const leftBtn = document.getElementById('leftBtn');
        const rightBtn = document.getElementById('rightBtn');

        // 初始化游戏
        function initGame() {
            canvas = document.getElementById('gameCanvas');
            ctx = canvas.getContext('2d');
            
            // 设置画布尺寸
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            
            // 初始化蛇
            resetSnake();
            
            // 生成食物
            generateFood();
            
            // 更新高分显示
            highScoreDisplay.textContent = highScore;
            
            // 绑定事件监听
            bindEvents();
            
            // 绘制初始状态
            draw();
        }

        // 调整画布尺寸
        function resizeCanvas() {
            const container = canvas.parentElement;
            const containerWidth = container.clientWidth;
            const containerHeight = Math.min(containerWidth, window.innerHeight * 0.6);
            
            // 确保画布尺寸是网格大小的倍数
            canvas.width = Math.floor(containerWidth / GRID_SIZE) * GRID_SIZE;
            canvas.height = Math.floor(containerHeight / GRID_SIZE) * GRID_SIZE;
        }

        // 重置蛇的状态
        function resetSnake() {
            const centerX = Math.floor(canvas.width / GRID_SIZE / 2) * GRID_SIZE;
            const centerY = Math.floor(canvas.height / GRID_SIZE / 2) * GRID_SIZE;
            
            snake = [
                {x: centerX, y: centerY},
                {x: centerX - GRID_SIZE, y: centerY},
                {x: centerX - GRID_SIZE * 2, y: centerY}
            ];
            
            direction = 'right';
            nextDirection = 'right';
            snakeLength = 3;
            score = 0;
            gameSpeed = INITIAL_SPEED;
            
            // 更新显示
            updateDisplays();
        }

        // 生成食物
        function generateFood() {
            const getRandomPosition = () => {
                const x = Math.floor(Math.random() * (canvas.width / GRID_SIZE)) * GRID_SIZE;
                const y = Math.floor(Math.random() * (canvas.height / GRID_SIZE)) * GRID_SIZE;
                return {x, y};
            };
            
            // 确保食物不会出现在蛇身上
            let position;
            do {
                position = getRandomPosition();
            } while (snake.some(segment => segment.x === position.x && segment.y === position.y));
            
            food = position;
            
            // 安排特殊食物的出现
            scheduleSpecialFood();
        }

        // 安排特殊食物的出现
        function scheduleSpecialFood() {
            // 清除之前的计时器
            if (specialFoodTimer) clearTimeout(specialFoodTimer);
            
            // 随机延迟后出现特殊食物
            const delay = Math.random() * 10000 + 5000; // 5-15秒
            specialFoodTimer = setTimeout(() => {
                generateSpecialFood();
            }, delay);
        }

        // 生成特殊食物
        function generateSpecialFood() {
            const getRandomPosition = () => {
                const x = Math.floor(Math.random() * (canvas.width / GRID_SIZE)) * GRID_SIZE;
                const y = Math.floor(Math.random() * (canvas.height / GRID_SIZE)) * GRID_SIZE;
                return {x, y};
            };
            
            // 确保特殊食物不会出现在蛇或普通食物上
            let position;
            do {
                position = getRandomPosition();
            } while (
                snake.some(segment => segment.x === position.x && segment.y === position.y) ||
                (food.x === position.x && food.y === position.y)
            );
            
            specialFood = position;
            specialFoodVisible = true;
            
            // 设置特殊食物的消失时间
            setTimeout(() => {
                specialFoodVisible = false;
                specialFood = null;
            }, SPECIAL_FOOD_DURATION);
        }

        // 绑定事件监听
        function bindEvents() {
            // 键盘控制
            window.addEventListener('keydown', handleKeyPress);
            
            // 按钮控制
            startBtn.addEventListener('click', startGame);
            pauseBtn.addEventListener('click', togglePause);
            resumeBtn.addEventListener('click', togglePause);
            restartBtn.addEventListener('click', restartGame);
            soundBtn.addEventListener('click', toggleSound);
            
            // 移动设备控制
            upBtn.addEventListener('click', () => setDirection('up'));
            downBtn.addEventListener('click', () => setDirection('down'));
            leftBtn.addEventListener('click', () => setDirection('left'));
            rightBtn.addEventListener('click', () => setDirection('right'));
        }

        // 处理键盘输入
        function handleKeyPress(e) {
            switch(e.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    setDirection('up');
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    setDirection('down');
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    setDirection('left');
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    setDirection('right');
                    break;
                case ' ':
                    togglePause();
                    break;
            }
        }

        // 设置方向
        function setDirection(newDirection) {
            // 防止180度转向
            const isOpposite = (
                (direction === 'up' && newDirection === 'down') ||
                (direction === 'down' && newDirection === 'up') ||
                (direction === 'left' && newDirection === 'right') ||
                (direction === 'right' && newDirection === 'left')
            );
            
            if (!isOpposite) {
                nextDirection = newDirection;
            }
        }

        // 开始游戏
        function startGame() {
            startScreen.classList.add('hidden');
            isPaused = false;
            isGameOver = false;
            gameLoop();
        }

        // 切换暂停状态
        function togglePause() {
            if (isGameOver) return;
            
            isPaused = !isPaused;
            
            if (isPaused) {
                pauseScreen.classList.remove('hidden');
                cancelAnimationFrame(gameLoopId);
            } else {
                pauseScreen.classList.add('hidden');
                gameLoop();
            }
        }

        // 重新开始游戏
        function restartGame() {
            resetSnake();
            generateFood();
            gameOverScreen.classList.add('hidden');
            isGameOver = false;
            gameLoop();
        }

        // 切换声音
        function toggleSound() {
            soundEnabled = !soundEnabled;
            soundIcon.className = soundEnabled ? 'fa fa-volume-up' : 'fa fa-volume-off';
        }

        // 游戏主循环
        function gameLoop() {
            if (isPaused || isGameOver) return;
            
            // 更新方向
            direction = nextDirection;
            
            // 移动蛇
            moveSnake();
            
            // 检查碰撞
            if (checkCollision()) {
                gameOver();
                return;
            }
            
            // 检查食物
            checkFood();
            
            // 绘制游戏
            draw();
            
            // 继续循环
            gameLoopId = setTimeout(gameLoop, gameSpeed);
        }

        // 移动蛇
        function moveSnake() {
            const head = {x: snake[0].x, y: snake[0].y};
            
            // 根据方向移动头部
            switch(direction) {
                case 'up':
                    head.y -= GRID_SIZE;
                    break;
                case 'down':
                    head.y += GRID_SIZE;
                    break;
                case 'left':
                    head.x -= GRID_SIZE;
                    break;
                case 'right':
                    head.x += GRID_SIZE;
                    break;
            }
            
            // 添加新头部
            snake.unshift(head);
            
            // 如果长度超过蛇的长度，移除尾部
            if (snake.length > snakeLength) {
                snake.pop();
            }
        }

        // 检查碰撞
        function checkCollision() {
            const head = snake[0];
            
            // 检查墙壁碰撞
            if (
                head.x < 0 || 
                head.x >= canvas.width || 
                head.y < 0 || 
                head.y >= canvas.height
            ) {
                return true;
            }
            
            // 检查自身碰撞
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            
            return false;
        }

        // 检查食物
        function checkFood() {
            const head = snake[0];
            
            // 检查普通食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数和长度
                score += NORMAL_FOOD_SCORE;
                snakeLength++;
                
                // 更新显示
                updateDisplays();
                
                // 播放吃食物音效
                if (soundEnabled) playEatSound();
                
                // 生成新食物
                generateFood();
                
                // 调整游戏速度
                adjustSpeed();
            }
            
            // 检查特殊食物
            if (specialFoodVisible && head.x === specialFood.x && head.y === specialFood.y) {
                // 增加额外分数
                score += SPECIAL_FOOD_SCORE;
                snakeLength += 2;
                
                // 更新显示
                updateDisplays();
                
                // 播放特殊食物音效
                if (soundEnabled) playSpecialEatSound();
                
                // 隐藏特殊食物
                specialFoodVisible = false;
                specialFood = null;
                
                // 调整游戏速度
                adjustSpeed();
            }
        }

        // 调整游戏速度
        function adjustSpeed() {
            // 随着分数增加，游戏速度加快（有最小值限制）
            gameSpeed = Math.max(MIN_SPEED, INITIAL_SPEED - Math.floor(score / 10) * SPEED_INCREMENT);
        }

        // 更新显示
        function updateDisplays() {
            scoreDisplay.textContent = score;
            lengthDisplay.textContent = snakeLength;
            
            // 更新高分
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('snakeHighScore', highScore);
                highScoreDisplay.textContent = highScore;
                gameOverHighScore.textContent = highScore;
            }
        }

        // 游戏结束
        function gameOver() {
            isGameOver = true;
            cancelAnimationFrame(gameLoopId);
            
            // 更新最终分数
            finalScore.textContent = score;
            gameOverHighScore.textContent = highScore;
            
            // 显示游戏结束界面
            gameOverScreen.classList.remove('hidden');
            
            // 播放游戏结束音效
            if (soundEnabled) playGameOverSound();
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = '#121212';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格（可选）
            drawGrid();
            
            // 绘制蛇
            drawSnake();
            
            // 绘制食物
            drawFood();
            
            // 绘制特殊食物（如果可见）
            if (specialFoodVisible) {
                drawSpecialFood();
            }
        }

        // 绘制网格
        function drawGrid() {
            ctx.strokeStyle = '#222222';
            ctx.lineWidth = 0.5;
            
            // 绘制垂直线
            for (let x = 0; x < canvas.width; x += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, canvas.height);
                ctx.stroke();
            }
            
            // 绘制水平线
            for (let y = 0; y < canvas.height; y += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(canvas.width, y);
                ctx.stroke();
            }
        }

        // 绘制蛇
        function drawSnake() {
            // 绘制蛇身
            snake.forEach((segment, index) => {
                // 蛇头和身体颜色不同
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#66BB6A';
                    
                    // 绘制眼睛
                    const eyeSize = GRID_SIZE / 6;
                    const eyeOffset = GRID_SIZE / 3;
                    
                    ctx.fillRect(segment.x, segment.y, GRID_SIZE, GRID_SIZE);
                    
                    // 根据方向绘制眼睛位置
                    ctx.fillStyle = '#FFFFFF';
                    switch(direction) {
                        case 'up':
                            ctx.fillRect(segment.x + eyeOffset, segment.y + eyeOffset, eyeSize, eyeSize);
                            ctx.fillRect(segment.x + GRID_SIZE - eyeOffset - eyeSize, segment.y + eyeOffset, eyeSize, eyeSize);
                            break;
                        case 'down':
                            ctx.fillRect(segment.x + eyeOffset, segment.y + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                            ctx.fillRect(segment.x + GRID_SIZE - eyeOffset - eyeSize, segment.y + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                            break;
                        case 'left':
                            ctx.fillRect(segment.x + eyeOffset, segment.y + eyeOffset, eyeSize, eyeSize);
                            ctx.fillRect(segment.x + eyeOffset, segment.y + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                            break;
                        case 'right':
                            ctx.fillRect(segment.x + GRID_SIZE - eyeOffset - eyeSize, segment.y + eyeOffset, eyeSize, eyeSize);
                            ctx.fillRect(segment.x + GRID_SIZE - eyeOffset - eyeSize, segment.y + GRID_SIZE - eyeOffset - eyeSize, eyeSize, eyeSize);
                            break;
                    }
                } else {
                    // 蛇身体
                    const colorIntensity = 0.8 - (index / snake.length * 0.4);
                    const rgbValue = Math.floor(75 * colorIntensity + 187 * (1 - colorIntensity));
                    ctx.fillStyle = `rgb(${rgbValue}, ${187}, ${rgbValue})`;
                    
                    // 绘制圆角矩形
                    const radius = GRID_SIZE / 5;
                    roundedRect(ctx, segment.x, segment.y, GRID_SIZE, GRID_SIZE, radius);
                    
                    // 绘制身体纹理
                    ctx.fillStyle = `rgba(255, 255, 255, 0.1)`;
                    if (index % 2 === 0) {
                        ctx.fillRect(segment.x + GRID_SIZE / 4, segment.y + GRID_SIZE / 4, GRID_SIZE / 2, GRID_SIZE / 2);
                    }
                }
            });
        }

        // 绘制圆角矩形
        function roundedRect(ctx, x, y, width, height, radius) {
            ctx.beginPath();
            ctx.moveTo(x + radius, y);
            ctx.lineTo(x + width - radius, y);
            ctx.arcTo(x + width, y, x + width, y + radius, radius);
            ctx.lineTo(x + width, y + height - radius);
            ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
            ctx.lineTo(x + radius, y + height);
            ctx.arcTo(x, y + height, x, y + height - radius, radius);
            ctx.lineTo(x, y + radius);
            ctx.arcTo(x, y, x + radius, y, radius);
            ctx.closePath();
            ctx.fill();
        }

        // 绘制食物
        function drawFood() {
            ctx.fillStyle = '#FF5722';
            
            // 绘制苹果形状
            ctx.beginPath();
            ctx.arc(food.x + GRID_SIZE / 2, food.y + GRID_SIZE / 3, GRID_SIZE / 3, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制果柄
            ctx.fillStyle = '#795548';
            ctx.fillRect(food.x + GRID_SIZE / 2, food.y, GRID_SIZE / 10, GRID_SIZE / 4);
        }

        // 绘制特殊食物
        function drawSpecialFood() {
            // 闪烁效果
            const time = Date.now();
            const alpha = 0.7 + 0.3 * Math.sin(time / 200);
            ctx.fillStyle = `rgba(255, 215, 0, ${alpha})`;
            
            // 绘制星形
            drawStar(ctx, specialFood.x + GRID_SIZE / 2, specialFood.y + GRID_SIZE / 2, 5, GRID_SIZE / 2, GRID_SIZE / 5);
            
            // 添加轮廓
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
            ctx.lineWidth = 2;
            ctx.stroke();
        }

        // 绘制星形
        function drawStar(ctx, cx, cy, spikes, outerRadius, innerRadius) {
            let rot = Math.PI / 2 * 3;
            let x = cx;
            let y = cy;
            let step = Math.PI / spikes;
            
            ctx.beginPath();
            ctx.moveTo(cx, cy - outerRadius);
            
            for (let i = 0; i < spikes; i++) {
                x = cx + Math.cos(rot) * outerRadius;
                y = cy + Math.sin(rot) * outerRadius;
                ctx.lineTo(x, y);
                rot += step;
                
                x = cx + Math.cos(rot) * innerRadius;
                y = cy + Math.sin(rot) * innerRadius;
                ctx.lineTo(x, y);
                rot += step;
            }
            
            ctx.lineTo(cx, cy - outerRadius);
            ctx.closePath();
            ctx.fill();
        }

        // 播放吃食物音效
        function playEatSound() {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioCtx.createOscillator();
            const gainNode = audioCtx.createGain();
            
            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // 音符 A
            oscillator.frequency.exponentialRampToValueAtTime(
                880, audioCtx.currentTime + 0.1
            );
            
            gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
            gainNode.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.01);
            gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 0.2);
            
            oscillator.connect(gainNode);
            gainNode.connect(audioCtx.destination);
            
            oscillator.start();
            oscillator.stop(audioCtx.currentTime + 0.2);
        }

        // 播放特殊食物音效
        function playSpecialEatSound() {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioCtx.createOscillator();
            const gainNode = audioCtx.createGain();
            
            oscillator.type = 'triangle';
            oscillator.frequency.setValueAtTime(660, audioCtx.currentTime); // 音符 E
            oscillator.frequency.exponentialRampToValueAtTime(
                1320, audioCtx.currentTime + 0.1
            );
            
            gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
            gainNode.gain.linearRampToValueAtTime(0.6, audioCtx.currentTime + 0.01);
            gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 0.3);
            
            oscillator.connect(gainNode);
            gainNode.connect(audioCtx.destination);
            
            oscillator.start();
            oscillator.stop(audioCtx.currentTime + 0.3);
        }

        // 播放游戏结束音效
        function playGameOverSound() {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioCtx.createOscillator();
            const gainNode = audioCtx.createGain();
            
            oscillator.type = 'sawtooth';
            oscillator.frequency.setValueAtTime(220, audioCtx.currentTime); // 音符 A
            oscillator.frequency.exponentialRampToValueAtTime(
                110, audioCtx.currentTime + 0.5
            );
            
            gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
            gainNode.gain.linearRampToValueAtTime(0.7, audioCtx.currentTime + 0.01);
            gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 0.8);
            
            oscillator.connect(gainNode);
            gainNode.connect(audioCtx.destination);
            
            oscillator.start();
            oscillator.stop(audioCtx.currentTime + 0.8);
        }

        // 初始化游戏
        window.onload = initGame;
    </script>
</body>
</html>
    